#!/usr/bin/python
# encoding=utf-8
# version: 2017-12-22 19:26:52

import sys
import os
import shutil

enter_cwd_dir = ''
python_file_dir = ''


class BundleInfo:
    def __init__(self, t_name='', t_code=''):
        self.bundle_name = t_name
        self.hash_code = t_code
        self.old_hash_code = ''

    def set_old_hash_code(self, t_code):
        self.old_hash_code = t_code

    def need_update(self):
        return self.hash_code != self.old_hash_code


def parse_arg(argv):
    if len(argv) != 1:
        return False, None
    return True, argv


def get_exe_path(simple_path):
    global enter_cwd_dir
    global python_file_dir
    return os.path.join(enter_cwd_dir, python_file_dir, simple_path)


def usage():
    print 'this is usage()'

if __name__ == '__main__':
    success, args = parse_arg(sys.argv)
    if not success:
        usage()
        exit(-1)
    enter_cwd_dir = os.getcwd()
    python_file_dir = os.path.dirname(sys.argv[0])

    sub_dir_name = './UpdateFiles/'

    if os.path.exists(get_exe_path('./ResVer.txt')) is False:
        print 'can not find ResVer.txt'
        exit(0)

    if os.path.exists(get_exe_path('./ResVer_Old.txt')) is False:
        print 'can not find ResVer_Old.txt'
        exit(0)

    bundle_info = {}
    with open(get_exe_path('./ResVer.txt'), 'r') as f:
        read_data = f.readlines()
        for read_line in read_data:
            if len(read_line.strip()) > 0:
                lines = read_line.strip().split(',', 2)
                if len(lines) == 3:
                    bundle_name = lines[0]
                    hash_code = lines[1]
                    if bundle_name in bundle_info:
                        print 'error: has two bundle with the same name'
                    else:
                        bundle_info[bundle_name] = BundleInfo(bundle_name, hash_code)

    with open(get_exe_path('./ResVer_Old.txt'), 'r') as f:
        read_data = f.readlines()
        for read_line in read_data:
            if len(read_line.strip()) > 0:
                lines = read_line.strip().split(',', 2)
                if len(lines) == 3:
                    bundle_name = lines[0]
                    hash_code = lines[1]
                    if bundle_name in bundle_info:
                        bundle_info[bundle_name].set_old_hash_code(hash_code)

    if os.path.isdir(get_exe_path(sub_dir_name)):
        shutil.rmtree(get_exe_path(sub_dir_name))
    os.mkdir(get_exe_path(sub_dir_name))

    for key in bundle_info.keys():
        if bundle_info[key].need_update():
            bundle_name = bundle_info[key].bundle_name
            if os.path.exists(os.path.join(get_exe_path('./'), bundle_name)):
                shutil.copy(os.path.join(get_exe_path('./'), bundle_name),
                            os.path.join(get_exe_path(sub_dir_name), bundle_name))
            else:
                print 'bundle {} can not find'.format(bundle_name)

    print 'finish'
